package com.itheima.tanhua.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.itheima.autoconfig.template.HuanXinTemplate;
import com.itheima.tanhua.api.db.QuestionsAPi;
import com.itheima.tanhua.api.db.UserServiceApi;
import com.itheima.tanhua.api.mongo.RecommendApi;
import com.itheima.tanhua.exception.ConsumerException;
import com.itheima.tanhua.interceptor.userHolder;
import com.itheima.tanhua.pojo.db.Question;
import com.itheima.tanhua.pojo.db.UserInfo;
import com.itheima.tanhua.pojo.mongo.RecommendUser;
import com.itheima.tanhua.until.JwtUtils;
import com.itheima.tanhua.until.mongo.Constants;
import com.itheima.tanhua.vo.mongo.pageResult;
import com.itheima.tanhua.vo.mongo.todayBestVo;
import io.jsonwebtoken.Claims;
import org.apache.dubbo.config.annotation.DubboReference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 芝士雪豹
 * @create 2022/9/22/15:13
 */
@Service
public class RecommendService {
    //远程调用
    @DubboReference
    private RecommendApi recommendApi;
    @DubboReference
    private UserServiceApi userServiceApi;
    @DubboReference
    private QuestionsAPi questionsAPi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    //今日佳人
    public todayBestVo todayBest(String token) {
        //过滤器已经做token是否有用了
        Claims claims = JwtUtils.getClaims(token);
        //根据token 获取当前用户id
        Long id = claims.get("id", Long.class);
        //远程调用 api接口 使用token查询到的id=toUserId 去查询缘分值最高的选手
        RecommendUser recommendUser = recommendApi.todayBest(id);
        //远程调用 根据查询用户id 来查需要的缘分最佳的用户
        UserInfo userInfo = userServiceApi.findById(recommendUser.getUserId());

        //创建需要返回给前端的对象
        todayBestVo todayBestVo = new todayBestVo();
        //把数据copy到 需要返回的数据
        BeanUtil.copyProperties(userInfo, todayBestVo);
        //进一步数据处理
        todayBestVo.setTags(userInfo.getTags().split(","));
        //将最大的 缘分值传入其中
        todayBestVo.setFateValue(Convert.toInt(recommendUser.getScore()));
        todayBestVo.setAge(userInfo.getAge());
        return todayBestVo;
    }

    public pageResult recommendation(String token, Integer page, Integer pageSize) {
        //过滤器已经做token是否有用了
        Claims claims = JwtUtils.getClaims(token);
        //根据token 获取当前用户id
        Long id = claims.get("id", Long.class);
        //创建空集合来接收所需数据
        List<Object> list = new ArrayList<>();
        //根据id查找 recommendUser表=id表
        List<RecommendUser> recommendUsers = recommendApi.findById(id);
        //stream流封装所需数据
        list = recommendUsers.stream().map(r -> {
            //创建今日最佳容器
            todayBestVo todayBestVo = new todayBestVo();
            //获取展示界面用户id
            Long userId = r.getUserId();
            //根据展示界面id查询用户具体信息
            UserInfo userInfo = userServiceApi.findById(userId);
            //把数据copy到 需要返回的数据
            BeanUtil.copyProperties(userInfo, todayBestVo);
            //进一步数据处理
            todayBestVo.setTags(userInfo.getTags().split(","));
            //将缘分值传入其中
            todayBestVo.setFateValue(Convert.toInt(r.getScore()));
            todayBestVo.setAge(userInfo.getAge());
            //将容器返回
            return todayBestVo;
        }).collect(Collectors.toList());
        //给到前端需要的所有属性
        return new pageResult(page, pageSize, list);
    }

    //查询佳人信息
    public todayBestVo personalInfo(Long userId) {
        //根据用户id查询用户信息
        UserInfo userInfo = userServiceApi.findById(userId);
        //根据操作人id 和查看人的用户id 查询两者的推荐值
        Integer score = recommendApi.queruserId(userId, userHolder.getId());
        //构建vo对象
        if (score == null) {
            score = 90;
        }
        todayBestVo vo = new todayBestVo();
        BeanUtil.copyProperties(userInfo, vo);
        vo.setTags(userInfo.getTags().split(","));
        vo.setFateValue(score);
        return vo;
    }

    //查询陌生人问题
    public String strangerQuestions(Long userId) {
        Question question = questionsAPi.findByUserId(userId);
        return question == null ? "你会唱跳,rap,篮球嘛?" : question.getTxt();
    }

    //回复陌生人问题
    public void replayQuestions(Long userId, String reply) {
        //获取当前用户id
        Long id = userHolder.getId();
        //查询当前用户数据
        UserInfo userInfo = userServiceApi.findById(id);
        //封装发送回答问题需要的属性
        Map map = new HashMap();
        map.put("userId", id);
        map.put("huanXinId", Constants.HX_USER_PREFIX + id);
        map.put("nickname", userInfo.getNickname());
        map.put("strangerQuestion", strangerQuestions(userId));
        map.put("reply", reply);
        //map 发前端不行 得转JSON
        String message = JSON.toJSONString(map);
        //调用templ 发送消息
        Boolean msg = huanXinTemplate.sendMsg(Constants.HX_USER_PREFIX + id, message);
        //true 就是发送成功
        if (!msg) {
            throw new ConsumerException("问题发送失败");
        }

    }
}
